package cn.leftshine.readme.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.SecondarySwitchDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.rometools.rome.feed.synd.SyndEntry;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import cn.leftshine.readme.R;
import cn.leftshine.readme.activity.base.BaseActivity;
import cn.leftshine.readme.beans.NewsItem;
import cn.leftshine.readme.event.NewsItemEvent;
import cn.leftshine.readme.fragment.ImageFragment;
import cn.leftshine.readme.fragment.NewsFragment;
import cn.leftshine.readme.fragment.base.BaseFragment;
import cn.leftshine.readme.helper.BottomNavigationViewHelper;
import cn.leftshine.readme.helper.DataNewsHelper;
import cn.leftshine.readme.helper.SettingsHelper;
import cn.leftshine.readme.helper.ThemeInfoHelper;
import solid.ren.skinlibrary.SkinLoaderListener;
import solid.ren.skinlibrary.loader.SkinManager;



public class MainActivity extends BaseActivity {

    private TextView mTextMessage;
    private FragmentManager mFragmentManager;
    //private NewsFragment newsFragment;
    private BaseFragment newsFragment,imageFragment;
    private ArrayList<BaseFragment> fragments = new ArrayList<>();
    private Drawer drawer;
    private Context context;
    private SettingsHelper settingsHelper;
    private BottomNavigationView bottomNavigationView;
    private SecondarySwitchDrawerItem itemNightMode;
    private Snackbar snackbar;
    private boolean isExitSnackbarShown;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.bottom_news:
                    switchFragment(newsFragment);
                    return true;
                case R.id.bottom_image:
                    switchFragment(imageFragment);
                    //getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,imageFragment).commit();
                    return true;
                case R.id.bottom_video:

                    return true;

                case R.id.bottom_more:

                    return true;
            }
            return false;
        }
    };

    private void switchFragment(BaseFragment showFragment) {
        fragmentTransaction = fragmentManager.beginTransaction();
        for(BaseFragment fragment:fragments){
            if(fragment == showFragment){
                fragmentTransaction.show(fragment);

            }else{
                fragmentTransaction.hide(fragment);
            }
        }
        //fragmentTransaction.replace(R.id.fragment_container,showFragment);
        fragmentTransaction.commit();
        invalidateOptionsMenu();


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentManager =getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();

        if (findViewById(R.id.fragment_container) != null) {

            // 不过，如果我们要从先前的状态还原，则无需执行任何操作而应返回，否则
            // 就会得到重叠的 Fragment。
            if (savedInstanceState != null) {
                return;
            }

            // 创建一个要放入 Activity 布局中的新 Fragment
            newsFragment = new NewsFragment();
            // 如果此 Activity 是通过 Intent 发出的特殊指令来启动的，
            // 请将该 Intent 的 extras 以参数形式传递给该 Fragment
            newsFragment.setArguments(getIntent().getExtras());
            imageFragment = new ImageFragment();
            imageFragment.setArguments(getIntent().getExtras());
            fragments.add(newsFragment);
            fragments.add(imageFragment);
            // 将该 Fragment 添加到“fragment_container” FrameLayout 中
            fragmentTransaction
                    .add(R.id.fragment_container,imageFragment)
                    .add(R.id.fragment_container, newsFragment)
                    .hide(imageFragment)
                    .show(newsFragment)
                    .commit();

        }

    }

    @Override
    protected void onResume() {
        //抽屉
        initDrawer();

        super.onResume();
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        context = this;
        settingsHelper = new SettingsHelper(context);
        mFragmentManager = getSupportFragmentManager();
        EventBus.getDefault().register(context);
    }
    @Override
    protected void initView() {
        mTextMessage = (TextView) findViewById(R.id.message);
        /*LinearLayout ll_bottom_navigation = findViewById(R.id.ll_bottom_navigation);
        dynamicAddView(ll_bottom_navigation, "background", R.color.color_bottom_navigation_bg);*/
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        snackbar  = Snackbar.make(bottomNavigationView,R.string.tip_one_more_click_to_exit,Snackbar.LENGTH_SHORT).setCallback(new Snackbar.Callback() {
            @Override
            public void onDismissed(Snackbar snackbar, int event) {
                isExitSnackbarShown = false;
                super.onDismissed(snackbar, event);
            }

            @Override
            public void onShown(Snackbar snackbar) {
                isExitSnackbarShown = true;
                super.onShown(snackbar);
            }
        });


        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        dynamicAddView(bottomNavigationView,"bottomNavigationTint",R.color.color_bottom_navigation_selected);


        dynamicAddView(snackbar.getView(),"background",R.color.colorAccent);

        TextView tvSnackbarText = (TextView)snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
        dynamicAddView(tvSnackbarText,"textColor",R.color.color_content_text);
    }

    @Override
    protected void initData() {}

    @Override
    protected void beforDestroy() {
        if(EventBus.getDefault().isRegistered(context)){
            EventBus.getDefault().unregister(context);

        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_night_mode:
                setNightMode(!settingsHelper.isNightMode());
                /*if(settingsHelper.isNightMode()){
                    //关闭夜间模式
                    settingsHelper.setNightmode(false);
                    SkinManager.getInstance().restoreDefaultTheme();
                }else{
                    //开启夜间模式
                    //加载皮肤时有个判断，所以需要先设置nightMode为true，若切换失败再设为false
                    settingsHelper.setNightmode(true);
                    SkinManager.getInstance().loadSkin("skin_black.skin",
                            new SkinLoaderListener() {
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess() {
                                    //Toast.makeText(getApplicationContext(), "切换成功", Toast.LENGTH_SHORT).show();
                                    showSnackbar(getString(R.string.tip_night_mode_success));
                                }

                                @Override
                                public void onFailed(String errMsg) {
                                    //切换夜间模式失败，把设置值重置为false
                                    settingsHelper.setNightmode(false);
                                    //Toast.makeText(getApplicationContext(), "切换失败:"+errMsg, Toast.LENGTH_SHORT).show();
                                    showSnackbar(getString(R.string.tip_night_mode_fail));
                                }

                                @Override
                                public void onProgress(int progress) {
                                    Log.i("Theme", "onProgress: "+progress);
                                }

                            }
                    );
                }*/
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen()) {//当前抽屉是打开的，则关闭
            drawer.closeDrawer();
            return;
        }

        /*if (mCurrentFragment instanceof WebViewFragment) {//如果当前的Fragment是WebViewFragment 则监听返回事件
            WebViewFragment webViewFragment = (WebViewFragment) mCurrentFragment;
            if (webViewFragment.canGoBack()) {
                webViewFragment.goBack();
                return;
            }
        }*/

        if(!isExitSnackbarShown) {
            showSnackbar(getString(R.string.tip_one_more_click_to_exit));
        }else{
            finish();
            System.exit(0);
        }

        /*long currentTick = System.currentTimeMillis();
        if (currentTick - lastBackKeyDownTick > MAX_DOUBLE_BACK_DURATION) {
            showSnackbar(R.string.tip_one_more_click_to_exit);
            lastBackKeyDownTick = currentTick;
        } else {
            finish();
            System.exit(0);
        }*/
    }

    boolean isItemNightModeSwitched;
    private void initDrawer() {
        PrimaryDrawerItem itemTheme = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.drawer_item_theme).withSelectable(false);
        itemNightMode =  new SecondarySwitchDrawerItem().withName("Night Mode").withIcon(R.mipmap.option_menu_night).withChecked(settingsHelper.isNightMode()).withOnCheckedChangeListener(onCheckedChangeListener).withIdentifier(2);
        PrimaryDrawerItem itemSettings = new PrimaryDrawerItem().withName(R.string.drawer_item_settings).withSelectable(false).withIdentifier(3);
        /*SecondaryDrawerItem item2 = new SecondaryDrawerItem().withIdentifier(2).withName(R.string.drawer_item_settings).withSelectable(false);*/
//create the drawer and remember the `Drawer` result object

        drawer = new DrawerBuilder()
                .withActivity(this)
                .addDrawerItems(
                        itemTheme,
                        itemNightMode,
                        new DividerDrawerItem(),
                        itemSettings
                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        // do something with the clicked item :D
                        if(drawerItem.getIdentifier()==1){
                            //Theme
                            Intent intent = new Intent(context,ThemeActivity.class);
                            startActivity(intent);
                        }else if(drawerItem.getIdentifier()==3){
                            //Settings
                        }
                        return true;
                    }
                })
                .withSelectedItem(-1)
                .withOnDrawerListener(new Drawer.OnDrawerListener() {
                    @Override
                    public void onDrawerOpened(View drawerView) {
                        //Log.i("Drawer", "onDrawerOpened: ");
                    }

                    @Override
                    public void onDrawerClosed(View drawerView) {
                        //Log.i("Drawer", "onDrawerClosed: ");
                        isItemNightModeSwitched = false;
                    }

                    @Override
                    public void onDrawerSlide(View drawerView, float slideOffset) {
                        //Log.i("Drawer", "onDrawerSlide: "+slideOffset);
                        if(!isItemNightModeSwitched){
                            itemNightMode.withChecked(settingsHelper.isNightMode());
                            drawer.updateItem(itemNightMode);
                        }
                        isItemNightModeSwitched = true;
                    }
                })
                .build();

        dynamicAddView(drawer.getRecyclerView(),"background",R.color.colorAccent);
    }

    OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener(){

        @Override
        public void onCheckedChanged(IDrawerItem drawerItem, CompoundButton buttonView, boolean isChecked) {
            if(drawerItem.getIdentifier() == 2 ) {
                //夜间模式isChecked是否打开
                setNightMode(isChecked);
            }

        }
    };

    private void setNightMode(boolean night) {
        if (night){
            settingsHelper.setNightmode(true);
            SkinManager.getInstance().loadSkin("night_mode",
                    new SkinLoaderListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess() {
                            //Toast.makeText(getApplicationContext(), "切换成功", Toast.LENGTH_SHORT).show();
                            showSnackbar(getString(R.string.tip_night_mode_on));
                        }

                        @Override
                        public void onFailed(String errMsg) {
                            //关闭switch
                            itemNightMode.withChecked(false);
                            //itemNightMode.withTextColorRes(R.color.color_content_text);
                            drawer.updateItem(itemNightMode);
                            settingsHelper.setNightmode(false);
                            //Toast.makeText(getApplicationContext(), "切换失败:"+errMsg, Toast.LENGTH_SHORT).show();
                            showSnackbar(getString(R.string.tip_night_mode_fail));
                        }

                        @Override
                        public void onProgress(int progress) {
                            Log.i("Theme", "onProgress: "+progress);
                        }

                    }
            );
        }else {
            settingsHelper.setNightmode(false);
            //SkinManager.getInstance().restoreDefaultTheme();
            String lastSkinFilename = settingsHelper.getLastThemeFilename();
            if (lastSkinFilename.equals(ThemeInfoHelper.DEFAULT_SKIN_FILE_NAME)) {
                SkinManager.getInstance().restoreDefaultTheme();
            } else {
                SkinManager.getInstance().loadSkin(lastSkinFilename,
                        new SkinLoaderListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess() {
                                //Toast.makeText(getApplicationContext(), getString(R.string.tip_theme_switch_success,skinName), Toast.LENGTH_SHORT).show();
                                showSnackbar(getString(R.string.tip_night_mode_off));
                            }

                            @Override
                            public void onFailed(String errMsg) {
                                //Toast.makeText(getApplicationContext(), getString(R.string.tip_theme_switch_fail, skinName), Toast.LENGTH_SHORT).show();
                                settingsHelper.setNightmode(true);
                                showSnackbar(getString(R.string.tip_night_mode_fail));
                            }

                            @Override
                            public void onProgress(int progress) {
                                Log.i("Theme", "onProgress: " + progress);
                            }

                        }
                );
            }
        }
    }

    private void showSnackbar(String tip) {
        snackbar.setText(tip);
        snackbar.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void NewsItemEvent(NewsItemEvent newsItemEvent) {
        NewsItem newsItem = newsItemEvent.getNewsItem();
        SyndEntry syndEntry = newsItem.getSyndEntry();
        int type = newsItem.getType();
        Intent intent = new Intent();
        Log.i("pcj", "onListFragmentInteraction: a item clicked:"+syndEntry.getTitle());
        switch (type){
            case DataNewsHelper.TYPE_RSS_ARTICLE:
                // intent = new Intent(MainActivity.this,NewsDetailActivity.class);
                intent.setClass(MainActivity.this,NewsDetailActivity.class);
                intent.putExtra("title",syndEntry.getTitle());
                intent.putExtra("link",syndEntry.getLink());
                intent.putExtra("pubDate",syndEntry.getPublishedDate());
                intent.putExtra("content",syndEntry.getDescription().getValue());
                intent.putStringArrayListExtra("imgList",newsItem.getImgList());
                startActivity(intent);
                break;
            case DataNewsHelper.TYPE_RSS_IMAGE_ARTICLE:
                intent.setClass(MainActivity.this,NewsDetailActivity.class);
                intent.putExtra("title",syndEntry.getTitle());
                intent.putExtra("link",syndEntry.getLink());
                intent.putExtra("pubDate",syndEntry.getPublishedDate());
                intent.putExtra("content",syndEntry.getDescription().getValue());
                intent.putStringArrayListExtra("imgList",newsItem.getImgList());
                startActivity(intent);
                break;

            case DataNewsHelper.TYPE_RSS_IMAGE_SINGLE:

                break;
            case DataNewsHelper.TYPE_RSS_IMAGE_MULTI:

                break;


        }



    }
}
